package com.xpc.rpc.provider.spring.scanner;

import com.xpc.rpc.annotation.DubboService;
import com.xpc.rpc.protocol.meta.ServiceMeta;
import com.xpc.rpc.provider.cache.ProviderHandlerMapCache;
import com.xpc.rpc.register.common.RegisterService;
import com.xpc.rpc.register.common.config.RegisterConfig;
import com.xpc.rpc.register.zookeeper.ZookeeperRegisterServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 扫描@DubboService注解
 */
public class DubboServiceScanner extends ClassScanner{

    private static final Logger LOGGER = LoggerFactory.getLogger(DubboServiceScanner.class);

    /**
     * 根据指定的包名获取所有的class文件，并过滤出标注了@DubboService注解的class
     */
    public void doScanDubboServiceByPackages(RegisterConfig registerConfig) throws Exception{
        List<String> classList = getClassList(registerConfig.getPackageName());
        if(classList == null || classList.isEmpty()) {
            return;
        }

        classList.forEach(item -> {
            try {
                Class<?> clazz = Class.forName(item);
                if(clazz.isInterface()) {
                    return;
                }
                DubboService dubboService = clazz.getAnnotation(DubboService.class);
                if(dubboService != null) {
                    String interfaceName = getServiceName(dubboService);
                    //将服务提供者注册到注册中心
                    ServiceMeta serviceMeta = new ServiceMeta();
                    serviceMeta.setInterfaceName(interfaceName);
                    serviceMeta.setApplicationName(registerConfig.getApplicationName());
                    serviceMeta.setServerPort(registerConfig.getServerPort());
                    serviceMeta.setServerAddress(registerConfig.getServerAddress());
                    serviceMeta.setRegisterPort(registerConfig.getRegisterPort());
                    RegisterService registerService = new ZookeeperRegisterServiceImpl();
                    registerService.init(registerConfig);
                    registerService.register(serviceMeta);
                    ProviderHandlerMapCache.put(interfaceName,clazz.newInstance());
                }
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                LOGGER.error("scan DubboService @Interface error {}",e);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    private static String getServiceName(DubboService dubboService) {
        //先取接口的class
        Class<?> interfaceClass = dubboService.interfaceClass();
        if(interfaceClass != null) {
            return interfaceClass.getName();
        }
        //如果接口class为空，就去接口名称
        return dubboService.interfaceName();
    }

}
